/**
* @description: 795. 区间子数组个数
* @author hewei
* @date 2022/8/26 16:35
* @version 1.0
*/

public class NumSubarrayBoundedMax {

    public static void main(String[] args) {
        NumSubarrayBoundedMax numSubarrayBoundedMax = new NumSubarrayBoundedMax();
        int[] nums = {73,55,36,5,55,14,9,7,72,52};
        System.out.println(numSubarrayBoundedMax.numSubarrayBoundedMax(nums, 32, 69));
    }

    public int numSubarrayBoundedMax1(int[] nums, int left, int right) {
        int l = 0;
        int r = 0;
        int ans = 0;
        while (r < nums.length) {
            while (r < nums.length && (nums[r] < left || nums[r] > right)) {
                if (nums[r] > right) l = r + 1;
                ++r;
            }
            int temp = r;
            while (r < nums.length && nums[r] <= right) {
                if (nums[r] >= left) {
                    temp = r;
                    ans += r - l + 1;
                } else ans += temp - l + 1;
                ++r;
            }
        }
        return ans;
    }

    int[] nums;
    public int numSubarrayBoundedMax(int[] nums, int left, int right) {
        this.nums = nums;
        return process(right) - process(left - 1);
    }

    public int process(int target) {
        int temp = 0;
        int res = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > target) {
                temp = i + 1;
            } else res += i - temp + 1;
        }
        return res;
    }
}
